﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Shohdi.DataHandler;
using DatabaseComponent;

public partial class OrganizationEN : System.Web.UI.Page
{

    long OrgnizationChartID
    {
        get
        {
            if (ViewState["OrgnizationChartID"] == null)
            {
                ViewState["OrgnizationChartID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["OrgnizationChartID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["OrgnizationChartID"].ToString()] = obj;

            }

            return (long)Session[ViewState["OrgnizationChartID"].ToString()];

        }
        set
        {
            if (ViewState["OrgnizationChartID"] == null)
            {
                ViewState["OrgnizationChartID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["OrgnizationChartID"].ToString()] = value;
        }   
        
    }


    OrgnizationChart objOrgnizationChart
    {
        get
        {
            if (ViewState["objOrgnizationChart"] == null)
            {
                ViewState["objOrgnizationChart"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["objOrgnizationChart"].ToString()] == null)
            {
                Session[ViewState["objOrgnizationChart"].ToString()] = new OrgnizationChart();

            }

            return (OrgnizationChart)Session[ViewState["objOrgnizationChart"].ToString()];

        }
        set
        {
            if (ViewState["objOrgnizationChart"] == null)
            {
                ViewState["objOrgnizationChart"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["objOrgnizationChart"].ToString()] = value;
        }
    }



    



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Oranization_chart_page))
            Response.Redirect("LoginEN.aspx");



        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Organiztion_chart_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }





    }





    /// <summary>
    /// this function will check RequestID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        
        if (OrgnizationChartID != -1 && OrgnizationChartID != OrganizationChartControl.getMainOrg())
        {
            objOrgnizationChart.ID = OrgnizationChartID;

            OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);

            List<OrgnizationChart> __lstOrgnizationChart = objOrgnizationChartDB.getOrgnizationChartByID(OrgnizationChartID);

            if (__lstOrgnizationChart.Count == 0)
            {
                objOrgnizationChart = new OrgnizationChart();
                btnDelete.Visible = false;
                OrgnizationChartID = -1;
                return;
            }


            objOrgnizationChart = __lstOrgnizationChart[0];

            btnDelete.Visible = true;

        }
        else
        {
            newOrg();
            return;

        }


        //if (Request["ID"] != null)
        //{
        //    try
        //    {
        //        OrgnizationChartID = long.Parse(Request["ID"]);
        //        OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);
        //        List<OrgnizationChart> lstOrgnizationChart = objOrgnizationChartDB.getOrgnizationChartByID(OrgnizationChartID);
        //        if (lstOrgnizationChart.Count > 0)
        //        {
        //            if (lstOrgnizationChart[0].ID == 1 || lstOrgnizationChart[0].StatusID == 2)
        //                throw new Exception();

        //            objOrgnizationChart = lstOrgnizationChart[0];
                    
        //        }
        //        else
        //        {
        //            throw new Exception();

        //        }


        //    }
        //    catch
        //    {
        //        Response.Redirect("OrganizationViewEN.aspx");
        //    }
        //}
        //else
        //{
        //    btnDelete.Visible = false;
           
        //}
    }



    /// <summary>
    /// this function for putting the form in new state
    /// </summary>
    protected void newOrg()
    {
        objOrgnizationChart = new OrgnizationChart();
        btnDelete.Visible = false;
        OrgnizationChartID = -1;
        clearAllControls();
    }


    /// <summary>
    /// this will bind the user data to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (OrgnizationChartID != -1)
        {
            

            

            if (objOrgnizationChart.ParentID != null)
            {
                oc1.set(objOrgnizationChart.ParentID.Value);
            }


            txtNameAR.Text = objOrgnizationChart.NameAR;
            txtNameEN.Text = objOrgnizationChart.NameEN;

            txtOrgCode.Text = objOrgnizationChart.OrgCode;


            bindddlTypes();


            ddlChartType.SelectedValue = objOrgnizationChart.ChartTypeID.ToString();


            
        }
    }



    
    protected void ocItem_ItemChanged(object sender, EventArgs e)
    {
        OrgnizationChartID = ocItem.get();
        checkID();
        BindAllControls();
    }



    


    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        objOrgnizationChart.ParentID = oc1.get();
        objOrgnizationChart.NameAR = txtNameAR.Text;
        objOrgnizationChart.NameEN = txtNameEN.Text;


        objOrgnizationChart.OrgCode = txtOrgCode.Text;
        if (objOrgnizationChart.OrgCode.Length > 9)
            objOrgnizationChart.OrgCode = objOrgnizationChart.OrgCode.Substring(0, 9);


        objOrgnizationChart.ChartTypeID = long.Parse(ddlChartType.SelectedValue);


        objOrgnizationChart.StatusID = 1;


            

        
    }


    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {

        oc1.set(-1);
        txtNameAR.Text = "";
        txtNameEN.Text = "";

        txtOrgCode.Text = "";


        objOrgnizationChart = new OrgnizationChart();
        
    }




    protected void Page_Load(object sender, EventArgs e)
    {
        

        Persons currentPerson = GlobalVars.getCurrentPerson();
        




        if (!Page.IsPostBack)
        {
            checkSecurityAndCustomizePage(currentPerson);

            //BindTree();


            checkID();

            bindddlTypes();

            BindAllControls();

            
            

        }
    }



   







   




    /// <summary>
    /// this function will Save the department
    /// </summary>
    protected void Save()
    {
        

        if (checkForRepeats())
        {
            OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);
            if (objOrgnizationChart.ID == -1)
            {
                objOrgnizationChartDB.Insert(objOrgnizationChart);
                clearAllControls();
                refreshTree();
                lblResult.Text = "Data saved ok.";

            }
            else
            {
                objOrgnizationChartDB.Update(objOrgnizationChart);
                refreshTree();
                BindAllControls();
                lblResult.Text = "Data saved ok.";
            }

            

        }
        

    }

    /// <summary>
    /// this function will check if the department exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (department exist before)</returns>
    protected bool checkForRepeats()
    {
        OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);



        List<OrgnizationChart> lstOldOrgnizationChart = objOrgnizationChartDB.getOrgnizationChartByNameAR(objOrgnizationChart.NameAR);

        List<OrgnizationChart> lstExist = new List<OrgnizationChart>( from objOrg in lstOldOrgnizationChart where (objOrg.ChartTypeID == objOrgnizationChart.ChartTypeID && objOrg.NameAR == objOrgnizationChart.NameAR && objOrg.ID != objOrgnizationChart.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


        lstOldOrgnizationChart = objOrgnizationChartDB.getOrgnizationChartByNameEN(objOrgnizationChart.NameEN);

        lstExist = new List<OrgnizationChart>(from objOrg in lstOldOrgnizationChart where (objOrg.ChartTypeID == objOrgnizationChart.ChartTypeID && objOrg.NameEN == objOrgnizationChart.NameEN && objOrg.ID != objOrgnizationChart.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }
                


           


       

        return true;

    }


    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {
       
            lblError.Text = "Error , an item with the same name and type is already found , choose a new Name or type";
        
    }







    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Organiztion_chart_page))
            return;


        if (Page.IsValid)
        {
            if (ddlChartType.Items.Count == 0)
            {
                lblError.Text = "You must choose a type for the item , if types is empty then this item cannot have the selected parent";
                return;
            }


            ReadAllControls();

           

            


            Save();


        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Organiztion_chart_page))
            return;


        ReadAllControls();

        if (objOrgnizationChart.ID == -1)
        {
            lblError.Text = "No item to delete";


        }






        OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);



        //if (objOrgnizationChart.lstChild.Count > 0 || objOrgnizationChart.lstEmployees.Count > 0)
        //{
            objOrgnizationChart.StatusID = 2;
            objOrgnizationChartDB.Update(objOrgnizationChart);
            lblResult.Text = "Deleted ok.";
            refreshTree();
            clearAllControls();
            return;
        //}


        

        

        //objOrgnizationChartDB.Delete(objOrgnizationChart);


        //lblResult.Text = "Deleted ok.";
        //refreshTree();
        //clearAllControls();
       





    }

    /// <summary>
    /// event handle the change in oc1 user control
    /// </summary>
    /// <param name="sender">the object sending this event</param>
    /// <param name="e">the args of the event</param>
    protected void oc1_ItemChanged(object sender, EventArgs e)
    {
        bindddlTypes();
    }



    /// <summary>
    /// this function will bind the drop down list having types
    /// </summary>
    protected void bindddlTypes()
    {
        long ID = oc1.get();

        OrgnizationChartDB objOrgnizationChartDB = new OrgnizationChartDB(ConnectionStrings.LMS);
        List<OrgnizationChart> lstOrgnizationChart = objOrgnizationChartDB.getOrgnizationChartByID(ID);

        if (lstOrgnizationChart.Count > 0)
        {


            ChartTypeDB objChartTypeDB = new ChartTypeDB(ConnectionStrings.LMS);
            List<ChartType> lstChartType = objChartTypeDB.Search(new ChartType());

            lstChartType = new List<ChartType>(from objChartType in lstChartType where objChartType.ID != (long)OrgnizationChartDB.ChartTypes.Company select objChartType);

            List<ChartType> lstNew = new List<ChartType>();

            lstNew = new List<ChartType>(from objCT in lstChartType where objCT.Weight > lstOrgnizationChart[0].objChartType.Weight select objCT);


            if (objOrgnizationChart.ID != -1)
            {
                foreach (OrgnizationChart objOrg in objOrgnizationChart.lstChild)
                {
                    lstNew = new List<ChartType>(from objCT in lstNew where objCT.Weight < objOrg.objChartType.Weight select objCT);
                }
            }
            
            
            ddlChartType.DataSource = lstNew;

            ddlChartType.DataTextField = "TypeNameEN";
            ddlChartType.DataValueField = "ID";
            ddlChartType.DataBind();
        }
        else
        {
            List<ChartType> lstNew1 = new List<ChartType>();


            ddlChartType.DataSource = lstNew1;
            ddlChartType.DataTextField = "TypeNameEN";
            ddlChartType.DataValueField = "ID";
            ddlChartType.DataBind();
            
        }


        

    }

    protected void tvOrganizations_SelectedNodeChanged(object sender, EventArgs e)
    {

        OrgnizationChartID = getTreeSelectedID();
        
            checkID();
            BindAllControls();
        



    }

    /// <summary>
    /// this function will refresh the tree
    /// </summary>
    protected void refreshTree()
    {
        //long ID = getTreeSelectedID();
        //BindTree();
        //setTreeSelectedStarter(ID, tvOrganizations);
    }


    /// <summary>
    /// this function will get the selected id from tree
    /// </summary>
    /// <returns></returns>
    protected long getTreeSelectedID()
    {
        long newLong = -1;
        try
        {
            newLong = long.Parse(tvOrganizations.SelectedValue);
        }
        catch
        {
            newLong = -1;
        }

        return newLong;
    }



    /// <summary>
    /// this function will bind the tree with all organizations
    /// </summary>
    protected void BindTree()
    {
        OrgnizationChartDB __objOrgnizationChart = new OrgnizationChartDB(ConnectionStrings.LMS);
        
        List<OrgnizationChart> __lstOrgnizationChart = __objOrgnizationChart.Select("", " where [ParentID] is NULL AND [StatusID] <> '2' ");

        OrganizationHierList __lstOrganizationHierList = new OrganizationHierList(__lstOrgnizationChart);

        tvOrganizations.DataSource = __lstOrganizationHierList;
        tvOrganizations.DataBind();
        tvOrganizations.CollapseAll();


    }


    /// <summary>
    /// this function for setting a node in tree selected recursive
    /// </summary>
    /// <param name="ID">The id of the item in the node</param>
    /// <param name="tvNew">the tree to set node in</param>
    protected void setTreeSelectedStarter(long ID,TreeView tvNew)
    {
        for (int i = 0; i < tvNew.Nodes.Count; i++)
        {
            if (setTreeSelected(ID, tvNew.Nodes[i]))
                return;

        }
    }

    /// <summary>
    /// this function for setting a node in tree selected recursive
    /// </summary>
    /// <param name="ID">The id of the item in the node</param>
    /// <param name="tnNew">the node to search in its childs</param>
    /// <returns>true if found and selected</returns>
    protected bool setTreeSelected(long ID, TreeNode tnNew)
    {
        if (tnNew.Value == ID.ToString())
        {

            ExpandNode(tnNew);

            tnNew.Select();

            

            return true;
        }

        for (int i = 0; i < tnNew.ChildNodes.Count; i++)
        {
            if (setTreeSelected(ID, tnNew.ChildNodes[i]))
                return true;
        }

        return false;



    }

    /// <summary>
    /// this function will expand the tree to a node
    /// </summary>
    /// <param name="tnNewIn">the node to expand to</param>
    protected void ExpandNode(TreeNode tnNewIn)
    {
        TreeNode tnNew = tnNewIn;

        tnNew.Expand();

        while (tnNew.Parent != null)
        {
            tnNew = tnNew.Parent;
            tnNew.Expand();

        }
    }



    protected void btnNew_Click(object sender, EventArgs e)
    {

        newOrg();
    }


}
